package meta.api.web.files.presentation;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import meta.api.web.account.businessinfo.UserInfo;
import meta.api.web.common.util.ApiUtil;
import meta.api.web.files.businesscontrol.FilesMngBusiCtrl;
import meta.api.web.files.presentation.form.FilesForm;
import meta.common.log.CmnLogger;
import meta.common.msg.MessageConst;
import meta.common.util.JsonUtil;
import meta.common.util.ListUtil;
import meta.common.util.WebUtil;

@Controller
@RequestMapping(value="api/files")
@Tag(name = "文件批量管理机能", description = "文件批量管理机能")
public class FilesMngController {

    private static final CmnLogger logger = CmnLogger.getLogger(FilesMngController.class);

    private static final String FUNC_NM = "文件批量管理机能";

    private static final String ERROR_MSG_DATA_ERROR= "请求数据错误";
    private static final String ERROR_MSG_DELETED_ERROR = "文件已删除";
    private static final String ERROR_MSG_UPDATE_ERROR= "批量更新文件失败";
    private static final String ERROR_MSG_DELETE_ERROR= "批量删除文件失败";
    private static final String ERROR_MSG_RESTORE_ERROR= "批量恢复文件失败";

    @Autowired
    private FilesMngBusiCtrl filesMngBusiCtrl;

    /**
     * 批量更新文件
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/update")
    @Operation(tags = "批量更新文件", description = "批量更新文件")
    public String update(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "批量更新文件", null);

        FilesForm inputData = JsonUtil.toObj(ApiUtil.readTxtBody(req), FilesForm.class);
        if (inputData == null
                || ListUtil.isEmptyList(inputData.getFilenames())) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        // 取得登录用户详细情报
        UserInfo loginUser = WebUtil.getLoginUser(req);

        for (String filename : inputData.getFilenames()) {
            // 检证文件是否存在
            if (!filesMngBusiCtrl.checkIsFileExisted(filename, null)) {
                ApiUtil.setNotFoundResponse(req, res);
                return null;
            }

            // 检证文件是否逻辑删除
            if (filesMngBusiCtrl.checkIsFileExisted(filename, false)) {
                ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DELETED_ERROR);
                return null;
            }

            // 检证权限
            if (!filesMngBusiCtrl.checkIsFileOwner(filename, loginUser.getId())) {
                ApiUtil.setForbiddenResponse(req, res);
                return null;
            }
        }

        // 更新文件
        try {
            filesMngBusiCtrl.updateFiles(inputData.getFilenames(),
                    inputData.convertToMetadataForm(), loginUser.getId());
            ApiUtil.setEmptyJsonResponse(res);
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_UPDATE_ERROR);
        }

        return null;
    }

    /**
     * 批量删除文件
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/delete")
    @Operation(tags = "批量删除文件", description = "批量删除文件")
    public String delete(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "批量删除文件", null);

        FilesForm inputData = JsonUtil.toObj(ApiUtil.readTxtBody(req), FilesForm.class);
        if (inputData == null
                || ListUtil.isEmptyList(inputData.getFilenames())) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        // 取得登录用户详细情报
        UserInfo loginUser = WebUtil.getLoginUser(req);

        for (String filename : inputData.getFilenames()) {
            // 检证文件是否存在
            if (!filesMngBusiCtrl.checkIsFileExisted(filename, null)) {
                ApiUtil.setNotFoundResponse(req, res);
                return null;
            }

            // 检证权限
            if (!filesMngBusiCtrl.checkIsFileOwner(filename, loginUser.getId())) {
                ApiUtil.setForbiddenResponse(req, res);
                return null;
            }
        }

        // 删除文件
        try {
            if (Boolean.TRUE.equals(inputData.getPhysically())) {
                // 物理删除
                filesMngBusiCtrl.deleteFilesByFilenames(inputData.getFilenames(), loginUser.getId());
            } else {
                // 逻辑删除
                filesMngBusiCtrl.updateFilesDeletedByFilenames(inputData.getFilenames(), loginUser.getId());
            }
            ApiUtil.setEmptyJsonResponse(res);
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DELETE_ERROR);
        }

        return null;
    }

    /**
     * 批量恢复文件
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/restore")
    @Operation(tags = "批量恢复文件", description = "批量恢复文件")
    public String restore(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "批量恢复文件", null);

        FilesForm inputData = JsonUtil.toObj(ApiUtil.readTxtBody(req), FilesForm.class);
        if (inputData == null
                || ListUtil.isEmptyList(inputData.getFilenames())) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        // 取得登录用户详细情报
        UserInfo loginUser = WebUtil.getLoginUser(req);

        for (String filename : inputData.getFilenames()) {
            // 检证文件是否存在
            if (!filesMngBusiCtrl.checkIsFileExisted(filename, null)) {
                ApiUtil.setNotFoundResponse(req, res);
                return null;
            }

            // 检证权限
            if (!filesMngBusiCtrl.checkIsFileOwner(filename, loginUser.getId())) {
                ApiUtil.setForbiddenResponse(req, res);
                return null;
            }
        }

        // 恢复文件
        try {
            filesMngBusiCtrl.updateFilesNotDeletedByFilenames(inputData.getFilenames(), loginUser.getId());
            ApiUtil.setEmptyJsonResponse(res);
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_RESTORE_ERROR);
        }

        return null;
    }
}
